package com.example.ktapplication.fragment

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.adapter.VideoListAdapter
import com.example.ktapplication.base.BaseTitleRvFragment
import com.example.ktapplication.bean.Media
import com.example.ktapplication.enum.StateLayoutMode
import com.example.ktapplication.model.SystemViewModel
import com.example.ktapplication.model.SystemViewModel.Companion.MEDIA_REQ_VIDEO
import com.example.ktapplication.utils.LogHelper
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.toJson
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.eventbus.Subscribe

class VideoListFragment : BaseTitleRvFragment() {

    private val viewModel by lazy {
        ViewModelProvider(this)[SystemViewModel::class.java]
    }

    companion object {
        const val PLAYER_TAB_INDEX = 1
    }

    private val videoListAdapter by lazy {
        VideoListAdapter().apply {
            itemCallBack = object : VideoListAdapter.OnItemClickListener {
                override fun onItemClick(media: Media) {
                    showToast(media.title)
                }
            }
        }
    }

    override fun initAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder> {
        return videoListAdapter
    }

    override fun onPause() {
        super.onPause()
        pausePlayer()
    }

    override fun onStop() {
        super.onStop()
        pausePlayer()
    }

    override fun isRegisterEvent(): Boolean {
        return true
    }

    override fun onDate(savedInstanceState: Bundle?) {
        viewModel.mediaData.observe(this) {
            LogHelper.e("---ext ${javaClass.simpleName} sysData >>> ${it.toJson()}")
            videoListAdapter.addData(it)
            loadDataFinish()
        }
        viewModel.addViewModelState {
            if (it != StateLayoutMode.CONTENT) {
                videoListAdapter.addData(mutableListOf())
                loadDataFinish()
            }
        }
    }

    override fun loadData() {
        viewModel.getMediaData(MEDIA_REQ_VIDEO)
    }

    override fun loadMoreData() {
        loadDataFinish()
    }

    private fun pausePlayer() {
        videoListAdapter.pausePlayer()
    }

    override fun backPressAction(): Boolean {
        val result = videoListAdapter.onBackPressed()
        return result
    }

    @Subscribe
    fun onMainClickMenu(event: Event.MainTab) { //菜单按钮事件
        if (event.position != PLAYER_TAB_INDEX) {
            pausePlayer()
        }
    }

}
